package com.arpa.wms.controller;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.validation.ValidationUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.enums.CustomerCheckStatusEnum;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.common.util.ArpaCloudUtil;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.ResultDO;
import com.arpa.wms.domain.dto.CarrierDTO;
import com.arpa.wms.domain.dto.CarrierauditDTO;
import com.arpa.wms.domain.entity.Carrier;
import com.arpa.wms.domain.enums.CarrierTypeEnum;
import com.arpa.wms.domain.vo.CarrierVO;
import com.arpa.wms.service.ICarrierService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import java.util.*;


/**
 * <p>
 * 承运商 Controller
 * </p>
 *
 * @author LEO
 * @since 2021-2-22
 */
@Api(tags = "承运商管理")
@RestController
@RequestMapping(value = "/Carrier", produces = "application/json;charset=UTF-8")
@Log4j2
public class CarrierController {

    private final ICarrierService iCarrierService;

    private final ArpaCloudUtil arpaCloudUtil;

    public CarrierController(ICarrierService iCarrierService,  ArpaCloudUtil arpaCloudUtil) {
        this.iCarrierService = iCarrierService;
        this.arpaCloudUtil = arpaCloudUtil;
    }

    /**
     * 获取 承运商 列表
     *
     * @param CarrierDto
     * @param
     * @return
     */
    @ApiOperation(value = "获取 承运商 列表", notes = "获取 承运商 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = CarrierVO.class))
    @NeedLogin
    @PostMapping("/list")
    public Result list(CarrierDTO CarrierDto) {
        try {
            CarrierDto.setGroupCode(UserUtil.getBranchCode());
            CarrierVO CarrierVosum = iCarrierService.queryListSum(CarrierDto);
            List<CarrierVO> carrierVoList = iCarrierService.queryList(CarrierDto);

            Page returnPage = new Page(CarrierDto.getPageNum(), CarrierDto.getPageSize());
            returnPage.setRecords(carrierVoList);
            returnPage.setTotal(CarrierVosum.getTotal());
            returnPage.setSumObject(CarrierVosum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 承运商
     *
     * @param entity  Warehouse
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 承运商 ", notes = "添加 承运商 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456")
    })
    @NeedLogin
    @PostMapping("/save")
    public Result create(@RequestBody @Validated(Carrier.Save.class) Carrier entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            // 根据承运商类型分组校验
            Set<ConstraintViolation<Carrier>> set = ValidationUtil.validate(entity, CarrierTypeEnum.validateGroupClass(entity.getCarrierType()));
            if (set != null && set.size() > 0) {
                throw new ServiceException(set.iterator().next().getMessage());
            }
            //承运商校验
            iCarrierService.validCarrier(entity,false);
            iCarrierService.insert(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取承运商详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取承运商详情", notes = "获取承运商详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "承运商code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Carrier.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result carrier(@PathVariable String code, HttpServletRequest request) {
        try {
            CarrierVO CarrierVo = iCarrierService.getOneInfo(code);
            return Result.ok().data(CarrierVo);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改承运商
     *
     * @param entity  承运商
     * @param request
     * @return
     */
    @ApiOperation(value = "修改承运商", notes = "修改承运商")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PutMapping()
    public Result update(@RequestBody @Validated(Carrier.Update.class) Carrier entity, HttpServletRequest request) {
        if (StrUtil.isBlank(entity.getCode())) {
            return Result.error("code不能为空");
        }
        // 根据承运商类型分组校验
        Set<ConstraintViolation<Carrier>> set = ValidationUtil.validate(entity, CarrierTypeEnum.validateGroupClass(entity.getCarrierType()));
        if (set != null && set.size() > 0) {
            throw new ServiceException(set.iterator().next().getMessage());
        }
        //承运商校验
        iCarrierService.validCarrier(entity,true);
        int updateNum = iCarrierService.update(entity);
        if (updateNum == 0) {
            return Result.error("没有更新数据！code:" + entity.getCode());
        } else {
            return Result.ok("修改成功,更新" + updateNum + "条数据！");
        }
    }

    /**
     * 删除 承运商
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 承运商 ", notes = "删除 承运商 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "String")
    })
    @NeedLogin
    @GetMapping(value = "")
    public Result remove(@RequestParam String codes, HttpServletRequest request) {
        return iCarrierService.remove(codes);
    }

    /**
     * 承运商类型
     *
     * @return
     */
    @ApiOperation(value = "承运商类型", notes = "承运商类型")
    @NeedLogin
    @GetMapping("/carrierTypes")
    public Result carrierTypes() {
        ArrayList<Map> resultList = new ArrayList<>();
        for (CarrierTypeEnum item : CarrierTypeEnum.values()) {
            HashMap<String, String> carrierMap = new HashMap<>();
            carrierMap.put("value", item.getValue());
            carrierMap.put("desc", item.getDesc());
            resultList.add(carrierMap);
        }
        return Result.ok().data(resultList);

    }



    /**
     * 承运商下拉列表
     *
     * @return
     */
    @ApiOperation(value = "承运商下拉列表 ", notes = "承运商下拉列表", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer ")
    })
    @NeedLogin
    @GetMapping("/dropdown")
    public Result dropdown() {
        //校验授权仓库code和货主code不能为空
        Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
        String groupCode = UserUtil.getBranchCode();
        List<String> shipmentCodes = authMap.get(CommonConst.SHIPMENT_CODES);

        if(StrUtil.isBlank(groupCode)){
            throw new ServiceException("用户所属组织为空，请重新登录");
        }

        List<Carrier> list = iCarrierService.list(new LambdaQueryWrapper<Carrier>()
                .eq(Carrier::getStatus, CustomerCheckStatusEnum.SUCCESS_CHECK.getCode())
                .eq(Carrier::getGroupCode,groupCode)
                //.eq(Carrier::getWarehouseCode, UserUtil.getLoginWarehouseCodeOrShipmentCode())
                .in(Carrier::getShipmentCode, shipmentCodes)
        );
        return Result.ok().data(list);


    }


    @ApiOperation(value = "快递模板类型下拉列表 ", notes = "快递模板类型下拉列表", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "qimenKey", value = "Key", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "accessToken", value = "电子面单客户账号/店铺授权token", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "waybillPassword", value = "电子面单密码", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "outerCode", value = "外部编码", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "platformType", value = "平台类型", required = true, paramType = "query", dataType = "String")
    })
    @NeedLogin
    @GetMapping("/cloudprintStandardTemplates")
    public ResultDO cloudprintStandardTemplates(@RequestParam String qimenKey,
                                              @RequestParam  String accessToken,
                                              @RequestParam  String waybillPassword,
                                              @RequestParam  String outerCode,
                                              @RequestParam(defaultValue = "CAINIAO")  String platformType) {

        int type = 1;
        if(StrUtil.equals(platformType,"JD")){
            type = 2;
        }else if(StrUtil.equals(platformType,"PDD")){
            type = 3;
        }else if(StrUtil.equals(platformType,"DY")){
            type = 4;
        }else if(StrUtil.equals(platformType,"TB")){
            type = 5;
        }else if(StrUtil.equals(platformType,"KS")){
            type = 6;
        }

        ResultDO resultDO = arpaCloudUtil.getCloudprintStandardTemplates(type,outerCode,accessToken,UserUtil.getBranchCode());
        //TODO 此处调用中台服务获取标准面单模板
        //List<StandardTemplateResult> standardTemplateResults = tmsWaybillUpdateService.getCloudprintStandardTemplates(qimenKey, waybillPassword, accessToken, outerCode);
        return resultDO;

    }

}
